/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package request.document;

import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import org.primefaces.model.UploadedFile;
import system.general.*;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "request_document")
@RequestScoped
public class Main extends Beans implements Serializable {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    private Path path = new Path();
    private Find request_documentFind = new Find();
    private List<Beans> request_documentList = new ArrayList<>();
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();
    private UploadedFile file;

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    private void load() {
        try {
            map.clear();
            map.put("id = " + logged.getDetailId(), " ");

            request_documentList.clear();
            request_documentList = request_documentFind.byMap(map);

            setId(request_documentList.get(0).getId());
            setId_solicitud(request_documentList.get(0).getId_solicitud());
            setRegistrado(request_documentList.get(0).getRegistrado());
            setDetalle(request_documentList.get(0).getDetalle());
            setArchivo(request_documentList.get(0).getArchivo());

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {

            if (file == null) {
                throw new Exc("m24");
            }
            if (val_extention() == false) {
                throw new Exc("m25");
            }

            map.clear();
            setId_solicitud(logged.getMasterId());

            map.put("id_solicitud = " + logged.getMasterId(), " AND ");
            map.put("detalle = '" + getDetalle(), "' ");

            //Verifica si el registro existe, de lo contrario lo inserta
            if (request_documentFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "INSERT INTO public.solicitud_documento (id_solicitud,registrado,detalle,archivo) "
                    + "VALUES ( " + logged.getMasterId() + ",CURRENT_TIMESTAMP,'" + getDetalle() + "','" + getArchivo() + "')";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            //Localiza el id del registro recien insertado, con la llave única
            request_documentList = request_documentFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setDetailId(request_documentList.get(0).getId());


            sql = "UPDATE public.solicitud_documento SET "
                    + "archivo='" + upLoad() + "' "
                    + "WHERE id =" + logged.getDetailId();

            persistencia.executeUpdate(sql);
            throw new Exc("m1");
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {

            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }

            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("id <> " + logged.getDetailId(), " AND ");
            map.put("id_solicitud = " + logged.getMasterId(), " AND ");
            map.put("archivo = '" + getArchivo(), "' ");

            if (request_documentFind.byExist(map)) {
                throw new Exc("m5");
            }
            if (file == null) {

                sql = "UPDATE public.solicitud_documento SET "
                        + "id_solicitud= " + logged.getMasterId() + ", "
                        + "detalle='" + getDetalle() + "' ,"
                        + "archivo='" + getArchivo() + "' "
                        + "WHERE id =" + logged.getDetailId();

            } else {

                if (val_extention() == false) {
                    throw new Exc("m25");
                } else {

                    upLoad();
                    sql = "UPDATE public.solicitud_documento SET "
                            + "id_solicitud= " + logged.getMasterId() + ", "
                            + "detalle='" + getDetalle() + "' ,"
                            + "archivo='" + getArchivo() + "'"
                            + "WHERE id =" + logged.getDetailId();
                }
            }

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m4");
            }

            File fileDelete = new File(path.getRequestPath() + getArchivo());

            //Elimina el resgistro por el id_persona
            deleteById(logged.getDetailId());
            fileDelete.delete();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        //Verifica si el usuario ya existe para otra persona
        sql = "DELETE FROM public.solicitud_documento "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
        File f = new File(path.getRequestPath() + getArchivo());

        f.delete();
        clear();
    }

    private boolean val_extention() {
        int pointPosition = file.getFileName().lastIndexOf(".");
        int lengthFileName = file.getFileName().length();
        String fileExtention = file.getFileName().substring(pointPosition + 1, lengthFileName);
        if (!fileExtention.equals("pdf")) {
            return false;
        }

        return true;
    }

    private String upLoad() {
        try {
            int pointPosition = file.getFileName().lastIndexOf(".");
            int lengthFileName = file.getFileName().length();
            String fileExtention = file.getFileName().substring(pointPosition + 1, lengthFileName);
            String fileName = "solicitud_" + String.valueOf(logged.getDetailId() + "." + fileExtention);
            FileOutputStream fOut = new FileOutputStream(path.getRequestPath() + fileName);
            InputStream fIn = getFile().getInputstream();
            byte data[] = new byte[1024];
            int bRead = -1;
            while ((bRead = fIn.read(data)) != -1) {
                fOut.write(data, 0, bRead);
            }
            fOut.flush();
            fOut.close();
            fOut = null;

            fIn.close();
            fIn = null;
            return fileName;
        } catch (IOException ex) {
            msg.showErr(namePackage(), "java", ex);
            return null;
        }
    }

    public void selectedUniversity(ValueChangeEvent event) throws Exc, SQLException, Exception {
        logged.setDetailId(0);
        logged.setMasterId(0);
        setId(0);
    }

    public void selectedFaculty(ValueChangeEvent event) throws Exc, SQLException, Exception {
        logged.setDetailId(0);
        setId(0);
        logged.setMasterId(Integer.parseInt(event.getNewValue().toString()));
    }

    public void selectedselectedidsolicitud(ValueChangeEvent event) throws Exc, SQLException, Exception {

        setId_solicitud(Integer.parseInt(event.getNewValue().toString()));
    }

    public void clear() {
        clearBeans();
        logged.setDetailId(0);
    }

    public void selectedtempId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
